package com.cykj.page02;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @BelongsProject: MyTomcat
 * @BelongsPackage: com.cykj.page02
 * @Author: WWJ
 * @CreateTime: 2025-06-25 17:01
 * @Description: 线程对象
 * @Version: 1.0
 */
public class MyTask implements Runnable{

    private Socket socket;

    public MyTask(Socket socket) {
        this.socket = socket;
    };
    @Override
    public void run() {
        try {
            while (true){
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len = inputStream.read(bytes);
                String request = new String(bytes, 0, len);
                System.out.println("客户端请求数据：\n" + request);
                MyHttpRequest httpRequest = new MyHttpRequest(request);
                String filePath ="webapps"+httpRequest.getRequestURL();
                File file = new File(filePath);
                if (httpRequest.getRequestURL().equals("/")){
                    filePath = "webapps/pages/index.html";
                }else if (!file.exists()){
                    filePath = "webapps/pages/404.html";
                }
                StaticResourceHandler staticResourceHandler = new StaticResourceHandler(filePath);
                //响应
                MyHttpResponse myHttpResponse = new MyHttpResponse(socket);
                myHttpResponse.write(staticResourceHandler.getMedia(),staticResourceHandler.getFileBytes());
                //线程自动结束
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
